import {
  getProductFields,
  getProductDetail,
  deleteProductByIds,
  unbindQrcode,
  productStatisticsInit,
  bindQrcode,
} from '@src/api/ProductApi';
import {
  setPageRelationProduct,
  getCardCache,
  setCardCache,
  productCheckAuth
} from '@src/api/ProductV2Api';
import {getCount} from '@src/api/ArchiveApi';
import { queryAppletQrCode, createAppletQrCode, getContractGray } from '@src/api/CustomerApi'
import { getStorageForDetailTabbar, setStorageForDetailTabbar } from '@src/api/SystemApi'
import {
  getEnabledCardInfo
} from '@src/api/SettingCusProApi';

import EventTable from '@src/modules/product/components/EventTable.vue';
import TaskTable from '@src/modules/product/components/TaskTable.vue';
import PlanTable from '@src/modules/product/components/PlanTable.vue';
import RemindTable from '@src/modules/product/components/RemindTable.vue';
import InfoRecord from '@src/modules/product/components/InfoRecord.vue';
import RemindDialog from '@src/modules/product/components/RemindDialog.vue';
import PublicDialog from '@src/modules/productV2/productView/components/PublicDialog.vue';
import DownloadCodeDialog from '@src/modules/product/components/DownloadCodeDialog.vue';
import TaskCard from '@src/modules/customer/view/components/TaskCard'
import QualityInfoRecord from '@src/modules/productV2/productView/components/QualityInfoRecord.vue'
import CustomerBind from './components/CustomerBind.vue'
import SmartPlanTable from '@src/modules/smartPlan/common/smartPlanTable.vue'
import CustomerContractTable from '@src/modules/customer/view/components/CustomerContractTable.vue';
import ProductQualityInfo from '@src/modules/productV2/productView/components/ProductQualityInfo.vue'
import ProductFaultLibraryTable from '@src/modules/productV2/productView/components/ProductFaultLibraryTable.vue'
import FormCellChange from '@src/component/compomentV2/FormCellChange/index.vue';

import EditContactDialog from '@src/modules/product/components/EditContactDialog.vue';
import ProductContactTable from '@src/modules/product/components/ProductContactTable.vue';
import MiniTable from '@src/modules/productV2/productMenu/WorkTree/compoment/MiniTable';
import CatalogView from '@src/modules/productV2/productView/components/CatalogView.vue';
import noAuth from '@src/modules/calendar/noAuth.vue'
import BaseEventTable from 'src/modules/event/components/BaseEventTable.vue'

import BaseTileLayoutTabBar from '@src/component/common/BaseTabBar/BaseTileLayoutTabBar.vue'
import { isShowCustomerRemind, isShowPlanTask } from '@shb-lib/version';

import qs from '@src/util/querystring';
import AuthUtil from '@src/util/auth';

import QRCode from 'qrcodejs2';
import _ from 'lodash';

import { storageGet, storageSet } from '@src/util/storage';
import * as StorageUtil from '@src/util/storage.ts'
import StorageModuleEnum from '@model/enum/StorageModuleEnum'
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import QualityMixin from '@src/mixins/qualityMixin/index.tsx'
import SuperQrCodeBhAnalysis from '@src/modules/productV2/bhAnalysis/grayMixins'
import ManualTriggerMixin from '@src/mixins/manualTriggerMixin'

import { useStateSystemViewLayout } from 'pub-bbx-utils'
const { getSystemViewLayout } = useStateSystemViewLayout()
/* service */
import { smoothQualityInfoFieldForFormView, buildQualityInfoFormDataForFormView } from '@service/QualityInfoService.ts'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum.ts'
import StorageKeyEnum from '@model/enum/StorageKeyEnum.ts'
import { isOpenData, openAccurateTab } from '@src/util/platform';
import BaseBarV3 from '@src/component/common/BaseTabBar/BaseTabBarV3.vue'
import { BaseTabBarUsualEnum, StorageHttpParamsForTerminalType, StorageHttpParamsForModuleType } from '@src/component/common/BaseTabBar/enum'
import { computedTabList } from '@src/util/tabBarUtils'
import { migration } from '@src/component/form/util';
import {
  PRODUCT_DETAIL
} from '@src/component/guide/productV2Store';
/* mixin */
import {
  VersionControlCustomerMixin,
  VersionControlProductMixin,
  VersionControlTaskMixin,
  VersionControlEventMixin
} from '@src/mixins/versionControlMixin'
import { cloneDeep } from '@src/util/type';

/**
 * todo
 * 1. 只判断是否开启了产品二维码功能，如果开启则启用显示二维码、关联等功能，如果没有则不显示产品二维码相关信息，不再判断自助门户设置✅
 * 2. 二维码字段处理
 * 3. 同步记录更新
 */
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { isNotUndefined } from '@src/util/type';
// import initData from './initData';
import * as FormUtil from '@src/component/form/util'

import { getOssUrl } from '@src/util/assets'
const noneImage1 = getOssUrl('/productV2/catalogNone.png')
const noneImage2 = getOssUrl('/productV2/qrcodeNone.png')
import { formatAddress } from 'pub-bbx-utils';
import { getRootWindow } from '@src/util/dom';

import { havePageButtonSetGray } from '@src/util/grayInfo'
import { pageButtonClick, getPageButtonListForView } from '@src/component/compomentV2/buttonSet/common'
import { ButtonGetTriggerModuleEnum, ButtonSetDetailForShowPositionEnum } from 'pub-bbx-global/pageType/dist/enum/ButtonSetEnum'

export default {
  name: 'product-view',
  inject: ['initData'],
  mixins: [
    ThemeMixin,
    QualityMixin,
    SuperQrCodeBhAnalysis,
    ManualTriggerMixin,
    VersionControlCustomerMixin,
    VersionControlProductMixin,
    VersionControlTaskMixin,
    VersionControlEventMixin,
  ],
  data() {
    let tableExtraAttrs = Object.freeze({
      border: true
    })
    const tabsName = {
      infoRecord: this.$t('product.detail.tabs.tab3'),
      task: this.$t('product.detail.tabs.tab4'),
      event: this.$t('product.detail.tabs.tab5'),
      contract: this.$t('product.detail.tabs.tab6'),
      smartPlan: this.$t('smartPlan.title'),
      plan: this.$t('product.detail.tabs.tab7'),
      remind: this.$t('product.detail.tabs.tab8'),
      qualityInfo: this.$t('product.detail.tabs.tab9'),
      productQualityInfo: this.$t('common.tabs.peoductWarrantyinfo'),
      faultLibrary: this.$t('product.detail.btns.faultRecord')
    }
    let sysLabelList = Object.freeze([{
      key: 'info-record',
      name: tabsName['infoRecord'],
      show: () => true
    }, {
      key: 'task-table',
      name: tabsName['task'],
      show: () => this._isShowTaskModule
    }, {
      key: 'event-table',
      name: tabsName['event'],
      show: () => this._isShowEventModule
    }, {
      key: 'product-contract',
      name: tabsName['contract'],
      show: () => this.contractBtnCray
    }, {
      key: 'plan-table',
      name: tabsName['plan'],
      show: () => this.allowCreatePlanTask && this.isShowPlanTask
    }, {
      key: 'remind-table',
      name: tabsName['remind'],
      show: () => this.isShowCustomerRemind
    },
    {
      key: 'quality-info-record',
      name: tabsName['qualityInfo'],
      show: () => this.isOpenQuality
    }
    ])
    return {
      noneImage1,
      noneImage2,
      // initData,
      isOpenData,
      loading: true,
      currTab: 'info-record',
      showWholeName: -1, // -1代表不显示展开icon 0代表收起 1代表展开
      newestProduct: null,
      tabs: [],
      statisticalData: {}, // tab统计数据

      dynamicProductFields: [], // 产品自定义字段
      currTabRight: 'info-record',
      collapseDirection: '',
      guideSearchModelSave: false,
      guideDropdownMenu: false,
      isGuide: false,
      popperOptions: {
        boundariesElement: 'viewport',
        removeOnDestroy: true,
      },
      dialogType: '',
      dataInfo: _.cloneDeep(this.initData.product) || {},
      tableExtraAttrs,
      sysLabelList,
      api: {
        getCardCache,
        setCardCache
      },
      archiveCount:0,
      isArchiveView:false,
      codeType:'qrcode', // 二维码类型 qrcode普通二维码， miniProgramCode 小程序二维码
      miniProgramCodeImg:'',
      appletCodeId:'', // 小程序码id
      productAuth: {},
      contractBtnCray: false, // 合同灰度
      tabBarList:[],
      tabLabelKey:BaseTabBarUsualEnum.TabBarListItemLabel,
      tabNameKey:BaseTabBarUsualEnum.TabBarListItemKey,
      rightTabBarLoading:false,
      tabsName,

      pageButtonSetGray:havePageButtonSetGray(),
      pageButtonList:[],
      pageButtonLoading:false,
      formCellCount:1,

      taskLayout: 2, // 布局方式 1:通栏 2:左右
      leftActiveTab: 'product-view',
      leftActiveTabItem: {},
      rightActiveTab: '',
      rightActiveTabItem: {},
      tabPosition: '', // 记录tab位置  left|right
      rightTabBarList : [],
      taskLayoutTabBarList: [] 
    };
  },
  provide(){
    return{
      changeDataInfo:this.changeDataInfo
    }
  },
  watch: {
    collapse(newValue) {
      sessionStorage.setItem(
        `product_menu_collapse_${this.product.id}`,
        newValue
      );
    },
    collapseDirection(newValue) {
      sessionStorage.setItem(
        `product_collapseDirection_${this.product.id}`,
        newValue
      );
    },
    isOpenQuality(newValue) {
      if (newValue) {
        this.setQualityTabStorage()
      }
    },
    hasViewProductAuth: {
      handler(newValue) {
        if (!newValue) {
          document.body.classList.add('body-no-auth')
        } else {
          document.body.classList.remove('body-no-auth')
        }
      },
      immediate: true
    },
    rightTabBarList: {
      deep: true,
      handler(newValue){
        if(newValue){
          this.taskLayoutTabBarList = cloneDeep([...this.leftTabBarList,...this.rightTabBarList].filter(item => item.tabShow));
        }
      }
    }
  },
  computed: {
    hidePartCollapse() {
      if(this.taskLayout === 2) return '';

      if(this.taskLayout === 1) {
        return this.tabPosition === 'left' ? 'right' : 'left';
      }
    },
    leftTabBarList(){
      return [
        {
          position: 'left',
          tabName: 'product-view',
          disabled: true,
          tabLabel: i18n.t('product.detail.tabs.tab1'),
          tabShow: true,
        },
        {
          position: 'left',
          tabName: 'catalog-view',
          disabled: true,
          tabLabel: i18n.t('common.base.productType'),
          tabShow: this.productMenuAuth && this.isOpenSuperCodePro,
        },
        {
          position: 'left',
          tabName: 'qrcode-view',
          disabled: true,
          tabLabel: this.productQrcodeTabLabel,
          tabShow: this.isQrcodeEnabled,
        }
      ]
    } ,
    isShowProductSuperQrcode() {
      return this._isShowProductSuperQrcode
    },
    isShowProductQrcode() {
      return this._isShowProductQrcode
    },
    // 产品目录是否分列展示
    productMenuSplit() {
      return this.initData?.tenantConfig?.productMenuSplit
    },
    // 启用产品超级二维码功能
    isQrcodeEnabled() {
      return this.initData.productConfig.qrcodeEnabled && (this.isShowProductSuperQrcode || this.isShowProductQrcode)
    },
    showBindCustomer(){
      return this.initData?.loginUser?.authorities?.PRODUCT_EDIT && this.initData?.productConfig?.productCreateUnBindCustomer && !this.initData?.product?.customerId
    },
    workTask() {
      return this.initData?.workTask || this.initData?.task || {};
    },
    isOpenSuperCodePro(){
      return this.initData?.openSuperCodePro && this.isShowProductSuperQrcode
    },
    productMenuAuth(){
      return this.initData?.loginUser?.authorities?.PRODUCT_CATALOG_VIEW
    },
    hasLinkman() {
      let field = this.dynamicProductFields.filter(
        (item) => item.formType == 'customer'
      )[0];
      return field && field.setting.customerOption?.linkman;
    },
    hasAddress() {
      let field = this.dynamicProductFields.filter(
        (item) => item.formType == 'customer'
      )[0];
      return field && field.setting.customerOption?.address;
    },
    product() {
      let productData = this.newestProduct || this.initData.product || {}

      return {
        ...productData,
        ...buildQualityInfoFormDataForFormView(productData)
      }
    },
    customer() {
      return this.product.customer || {};
    },
    /** 客户是否被禁用 */
    isDisable() {
      return this.customer.status == null || this.customer.status === 0;
    },
    /**
     * 满足以下条件允许编辑客户
     * 1. 客户没有被删除
     * 2. 有客户编辑权限
     */
    allowEditCustomer() {
      return !this.isDelete && this.hasEditCustomerAuth;
    },
    /**
     * 客户是否被删除
     * 在客户删除时不允许做任何操作，只能查询
     * 所有操作的权限应该以此为基础
     */
    isDelete() {
      return this.customer.isDelete === null || this.customer.isDelete === 1;
    },
    /**
     * 是否有编辑客户权限，需要满足以下条件之一：
     *
     * 1. 编辑客户全部权限： 全部客户
     * 2. 编辑客户团队权限： 没有团队的客户都可编辑，有团队的按团队匹配。 包含个人权限
     * 3. 编辑客户个人权限： 自己创建的 或 客户负责人
     */
    hasEditCustomerAuth() {
      let customer = this.customer;
      let loginUserId = this.loginUser.userId;
      return AuthUtil.hasAuthWithDataLevel(
        this.permission,
        'CUSTOMER_EDIT',
        // 团队权限判断
        () => {
          let tags = Array.isArray(customer.tags) ? customer.tags : [];
          // 无团队则任何人都可编辑
          if (tags.length == 0) return true;

          let loginUserTagIds = this.initData.loginUser.tagIdsWithChildTag || [];
          return tags.some((tag) => loginUserTagIds.indexOf(tag.id) >= 0);
        },
        // 个人权限判断
        () => {
          return customer.createUser == loginUserId || this.isCustomerManagerOrSynergies;
        }
      );
    },
    eventTypes() {
      if (!this.initData || (this.initData && !this.initData.eventTypeInfo))
        return [];
      return this.initData.eventTypeInfo.map((t) => Object.freeze(t));
    },
    // 工单类型列表
    taskTypes() {
      if(!this.initData?.taskTypeInfo?.length) return []
      return this.initData.taskTypeInfo.map((t) => Object.freeze(t));
    },
    // 计划任务类型列表
    planTypeInfo() {
      if(!this.initData?.planTypeInfo?.length) return []
      return this.initData.planTypeInfo.map((t) => Object.freeze(t));
    },
    fields() {
      let fixedFields = [
        {
          displayName: '',
          formType: 'separator',
        },
        {
          displayName: this.$t('common.base.createUser'),
          fieldName: 'createUser',
          formType: 'user',
          isSystem: 1,
          orderId: 10001,
        },
        {
          displayName: this.$t('common.base.createTime'),
          fieldName: 'createTime',
          formType: 'datetime',
          isSystem: 1,
          orderId: 10002,
        },
        {
          displayName: this.$t('product.detail.type.id'),
          fieldName: 'id',
          formType: 'text',
          isSystem: 1,
          orderId: 10003,
        },
      ];

      if (this.initData?.productConfig?.qrcodeEnabled && (this._isShowProductSuperQrcode || this._isShowProductQrcode)) {
        fixedFields.push({
          displayName: this.$t('product.type.qrcodeId'),
          fieldName: 'qrcodeId',
          isSystem: 1,
          formType: 'text',
          orderId: 10000,
        });
      }

      let fields = this.dynamicProductFields
        .concat(fixedFields)
        .filter(f => {

          const fieldNameByVersionShowMap = {
            // catalogId: this._isShowProductType,
            qualityInfo: this._isShowProductQuality
          }

          const isShow = fieldNameByVersionShowMap[f.fieldName]
          if (isNotUndefined(isShow)) {
            return isShow
          }

          return f
        })
        .sort((a, b) => a.orderId - b.orderId);

      return smoothQualityInfoFieldForFormView(fields)
    },
    productId() {
      return this.product.id;
    },
    downloadCodeData() {
      return {
        qrcodeId: this.dataInfo.qrcodeId,
        nickName: this.initData.nickName,
        domain: this.initData.domain,
        codeType:this.codeType,
        miniProgramCodeImg:this.miniProgramCodeImg,
        appletCodeId:this.appletCodeId
      };
    },
    /** 子组件所需的数据 */
    propsForSubComponents() {
      return {
        customer: this.customer,
        product: this.product,
        loginUser: this.initData.loginUser,
        allowEditProduct: this.allowEditProduct,
        isDelete: this.isDelete,
        isDisable: this.isDisable,
        allowEditCustomer: this.allowEditCustomer,
        collapseDirection:this.collapseDirection,
        // isPhoneUnique: this.initData.isPhoneUnique,
        cardType:'product',
        loading:this.loading,
        cardAuth:this.allowEditProduct && !this.isDelete,
        archiveCount:this.archiveCount,
        isArchiveView:this.isArchiveView
      };
    },
    /** 当前登录的用户 */
    loginUser() {
      return this.initData.loginUser || {};
    },
    /** 当前用户的权限 */
    permission() {
      return this.initData?.loginUser?.authorities || {}
    },
    /** 是否显示返回按钮 */
    allowBack() {
      let allow = true;
      // 如果带入noHistory参数，则不显示
      let query = qs.parse(window.location.search);
      if (query.noHistory) return false;

      return allow;
    },

    allowDeleteProduct() {
      // fix: 33358
      return this.productAuth.deleted
      // return this.allowEditProduct && this.permission.PRODUCT_DELETE
    },
    /**
     * 满足以下条件允许编辑产品
     * 1. 产品没有被删除
     * 2. 有产品编辑权限
     */
    allowEditProduct() {
      return this.hasEditProductAuth // 权限改动去掉客户相关的
      // return !this.isDelete && this.hasEditProductAuth
    },
    /**
     * 满足以下提交见允许创建工单
     *
     * 1. 客户没被删除
     * 2. 客户没被禁用
     * 3. 产品编辑权限
     * 4. 创建工单权限
     * 5. 开启客户解绑的时候需要关联客户才能有权限
     */
    allowCreateTask() {
      let allowCreateTask = (
        !this.isDelete
        && this.hasEditProductAuth
        && AuthUtil.hasAuth(this.permission, 'TASK_ADD')
      );
      if(this.initData?.productConfig?.productCreateUnBindCustomer){
        allowCreateTask = allowCreateTask && this.initData?.product?.customerId
      }
      return allowCreateTask && this._isShowTaskModule && this.product.productStatus
    },
    /**
     * 满足以下提交可以创建事件
     *
     * 1. 客户没有被删除
     * 2. 客户没有被禁用
     * 3. 产品编辑权限
     * 4. 新建事件权限
     * 5. 开启客户解绑的时候需要关联客户才能有权限
     */
    allowCreateEvent() {
      let allowCreateEvent = (
        !this.isDelete
        && this.hasEditProductAuth
        && AuthUtil.hasAuth(this.permission, 'CASE_ADD')
      );
      if(this.initData?.productConfig?.productCreateUnBindCustomer){
        allowCreateEvent = allowCreateEvent && this.initData?.product?.customerId
      }
      return allowCreateEvent && this.product.productStatus
    },
    /**
     * 满足以下条件可以创建计划任务
     *
     * 1. 客户没有被删除
     * 2. 客户没有被禁用
     * 3. 启用计划任务
     * 4. 产品编辑权限
     * 5. 工单新建权限和工单指派权限
     * 6. 开启客户解绑的时候需要关联客户才能有权限
     */
    allowCreatePlanTask() {
      let planTaskEnabled = this.initData.planTaskEnabled;
      let allowCreatePlanTask = (
        !this.isDelete
        && this.hasEditProductAuth
        && planTaskEnabled
        && AuthUtil.hasEveryAuth(this.permission, ['TASK_ADD', 'TASK_DISPATCH', 'VIP_TASK_PLAN'])
      );
      if(this.initData?.productConfig?.productCreateUnBindCustomer){
        allowCreatePlanTask = allowCreatePlanTask && this.initData?.product?.customerId
      }
      return allowCreatePlanTask && this.product.productStatus
    },
    /**
     * 当前用户是否是该客户负责人
     * 客户负责人用于和客户创建人相同权限
     */
    isCustomerManager() {
      return this.loginUser.userId === this.product.customer?.customerManager;
    },

    /**
     * 当前用户是否是该客户协同人
    */
    isCustomerSynergies() {
      let customerSynergies = this.product.customer?.synergies || []
      return !!customerSynergies.find(v => v.userId === this.loginUser.userId)
    },

    /**
     * 当前用户是否是该客户负责人或协同人
     */
    isCustomerManagerOrSynergies() {
      return this.isCustomerManager || this.isCustomerSynergies
    },

    // 是否有编辑产品权限
    hasEditProductAuth() {
      // fix: 33358
      return this.productAuth.update
      // return this.authCheck(this.permission, 'PRODUCT_EDIT') || this.hasExtraEditAuth()
    },
    // 是否有查看产品权限
    hasViewProductAuth() {
      // return this.authCheck(this.permission, 'PRODUCT_VIEW')
      // 改为由接口判断
      return this.productAuth.check
    },
    auth () {
      return this.initData?.loginUser?.authorities || this.initData?.authorities
    },
    canProductCodeProduct() {
      return this.auth?.PRODUCT_CODE_PRODUCT
    },
    canProductCodeDownload() {
      return this.auth?.PRODUCT_CODE_DOWNLOAD
    },
    /* 是否显示客户提醒 */
    isShowCustomerRemind() {
      return this._isShowProductRemind
    },
    /* 是否显示计划任务 */
    isShowPlanTask() {
      return this._isShowTaskPlanTask && !this.smartPlanGray
    },
    // 是否显示更多操作
    isShowMoreOperation() {
      return this.isShowCreateSmartPlan || (this.pageButtonSetGray && this.pageButtonList.length)
    },
    /**
     * @description 显示折叠按钮
     * 审核结算、客户评价、附加组件有任一存在即显示
     */
    showCollapse() {
      return true;
    },
    productQrcodeTabLabel() {
      return this.isShowProductSuperQrcode ? this.$t('product.detail.tabs.tab2_super') : this.$t('product.detail.tabs.tab2')
    },
    productQrcodeNoRelationTip() {
      return this.isShowProductSuperQrcode ? this.$t('product.detail.tips.tip2_super') : this.$t('product.detail.tips.tip2')
    },
    productQrcodeNoRelationButtonText() {
      return this.isShowProductSuperQrcode ? this.$t('product.detail.btns.btn4_super') : this.$t('product.detail.btns.btn4')
    },
    // 故障库
    isShowFaultLibrary() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.NEW_FAULT_LIBRARY || false
    },
  },
  async created() {
    // 折叠面板缓存
    let collapse = sessionStorage.getItem(
      `product_collapse_${this.product.id}`
    );
    let collapseDirection = sessionStorage.getItem(
      `product_collapseDirection_${this.product.id}`
    );
    this.collapse = JSON.parse(collapse || 'true');
    this.collapseDirection = collapseDirection || '';

    if(this.pageButtonSetGray){
      this.getPageButtonListForView(ButtonGetTriggerModuleEnum.Product, ButtonSetDetailForShowPositionEnum.PcDetail,  {}, (list)=>{
        this.pageButtonList = list
      })
    }
  },
  async mounted() {
    await this.productCheckAuth()
    await this.getContractGray()

    if (!this.hasViewProductAuth){
      this.loading = false;
      return;
    }

    try {
      // 获取产品自定义字段
      let res = await getProductFields({
        isFromSetting: false,
      });
      this.dynamicProductFields = res.data || [];
      // 是否开启产品目录分列展示
      if (this.productMenuSplit) {
        this.dynamicProductFields.push({
          displayName: this.$t('common.base.productMenu'),
          fieldName: 'productMenu',
          formType: 'productMenu',
          export: true,
          isSystem: 1,
          orderId: this.dynamicProductFields.find(f => f.fieldName == 'catalogId')?.orderId - 1,
          tableName: 'product',
          setting: {},
        });
      }

    // 处理富文本
    this.newestProduct = await FormUtil.initRichTextContent(this.dynamicProductFields, this.initData.product)

    // this.updateProductNameStyle();
    this.$nextTick(()=>{

      this.createCode();
    })
    this.getTriggerList(['product', 'PRODUCT_ADDITIONAL'])
    await this.fetchStatisticalData();
    // this.refreshProduct();

    this.$nextTick(() => {
      if (storageGet(PRODUCT_DETAIL) && storageGet(PRODUCT_DETAIL) > 0) this.$Guide().destroy('product-product-detail')
      else this.$Guide([{
        content: this.$t('product.detail.guide.content1'),
        haveStep: true,
        nowStep: 1,
        id: 'product-product-detail',
        domObj:()=>{
          let dom = document.getElementById('product-product-detail-1').getElementsByClassName('el-tabs__item')[0]
          return dom
        },
        finishBtn: 'ok',
      }, {
        content: this.$t('product.detail.guide.content2'),
        haveStep: true,
        domObj:()=>{
          let dom = document.getElementById('product-product-detail-1').getElementsByClassName('el-tabs__item')[1]
          return dom
        },
        nowStep: 2,
        id: 'product-product-detail',
        finishBtn: 'ok',
      }, {
        content: this.$t('product.detail.guide.content3'),
        haveStep: true,
        nowStep: 3,
        domObj:()=>{
          let dom = document.getElementById('product-product-detail-1').getElementsByClassName('el-tabs__item')[2]
          return dom
        },
        id: 'product-product-detail',
        finishBtn: 'ok',
      }], 0, '', (e) => {
        return new Promise((resolve, reject) => {
          resolve()
        })
      }).create().then(res_=>{if(res_)storageSet(PRODUCT_DETAIL, '3')})
    })

    this.$eventBus.$on(
      'product_view.open_remind_dialog',
      this.openRemindDialog
    ); // 打开提醒弹窗
    // this.$eventBus.$on("product_view.update_detail", this.refreshProduct); // 更新详情
    this.$eventBus.$on('product_view_record_update', this.fetchStatisticalData); // 更新动态
    this.$eventBus.$on('product_view_remind_update', this.fetchStatisticalData); // 更新提醒
    this.$eventBus.$on('product_view_plan_update', this.fetchStatisticalData); // 更新计划任务
    this.$eventBus.$on('product_view.select_tab', this.selectTab);

    await this.getCount()
    this.queryAppletQrCode(this.dataInfo.qrcodeId)
    this.initRightTabBar();

    this.changeDataInfo(this.dataInfo, 'catalogPathName')
  } catch (error) {
    console.error('product-view fetch product error', error);
  }  finally {
    this.loading = false;
  }
  },
  beforeDestroy() {
    this.$eventBus.$off(
      'product_view.open_remind_dialog',
      this.openRemindDialog
    );
    // this.$eventBus.$off("product_view.update_detail", this.refreshProduct);
    this.$eventBus.$off(
      'product_view_record_update',
      this.fetchStatisticalData
    );
    this.$eventBus.$off(
      'product_view_remind_update',
      this.fetchStatisticalData
    );
    this.$eventBus.$off('product_view.select_tab', this.selectTab);
  },
  methods: {
    getPageButtonListForView,
    // 自定义按钮点击事件
    handlePageButtonClick(item) {
      pageButtonClick(item, [this.product], {
        fields: this.fields,
        multipleSelection: this.multipleSelection,
        js_vm: this,
      })
    },

    changeTaskDetailLayout(type, columns) {
      this.leftActiveTab = this.leftTabBarList[0].tabName 
      this.taskLayout = type;
      this.tabPosition = 'left';
      if(type === 2) {
        this.rightActiveTab = this.rightTabBarList[0].tabName;
      }
      this.formCellCount = columns * 1
    },
    openBaseLayoutModal() {
      this.$refs.bizLayoutModal.open()
    },
    // 获取合同灰度
    getContractGray() {
      getContractGray({
        code: 'CONTRACT'
      }).then(res => {
        if (res.succ) {
          this.contractBtnCray = res.data.CONTRACT;
        }
      })
    },
    async productCheckAuth() {
      let params = {
        productId: this.productId
      }
      try {
        let res = await productCheckAuth(params)
        if (res.code !== 0) return

        this.productAuth = res.result || {}
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * 是否有xx产品权限，需要满足以下条件之一：
     *
     * 1. xx产品全部权限： 全部产品
     * 2. xx产品团队权限： 创建人没有团队的产品都可xx，有团队的按团队匹配。 包含个人权限
     * 3. xx产品个人权限： 自己创建的产品 或 客户负责人的产品
     */
    authCheck(source, type) {
      let customer = this.product.customer;
      let loginUserId = this.loginUser.userId;
      return AuthUtil.hasAuthWithDataLevel(
        source,
        type,
        // 团队权限判断
        () => {
          // 未关联客户则由个人权限决定
          if (!customer) return false
          let tags = Array.isArray(customer.tags) ? customer.tags : [];
          // 无团队则任何人都可编辑
          if (!tags.length) return true;

          let loginUserTagIds = this.initData.loginUser.tagIds || [];
          return tags.some((tag) => loginUserTagIds.indexOf(tag.id) >= 0);
        },
        // 个人权限判断
        () => {
          // 未关联客户则仅判断是否为产品创建人
          let ifProductCreator = this.product?.createUser?.userId === loginUserId;

          if (!customer) return ifProductCreator;

          return ifProductCreator || this.isCustomerManagerOrSynergies;
        }
      );
    },


    // 查看行为分析
    goQrcode(qrcodeId){
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `product_bhAnalysis_${qrcodeId}`,
      //   title: '超级二维码行为分析',
      //   close: true,
      //   url: `/product/bhAnalysis?qrcode=${qrcodeId}&noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductBhAnalysis,
        key: qrcodeId,
        params: `qrcode=${qrcodeId}&noHistory=1`,
        fromId
      })
    },

    // 是否有额外配置的编辑产品权限（建立在原编辑权限已判断为false的情况下）
    hasExtraEditAuth() {
      let editAuth = this.permission['PRODUCT_EDIT'] || 0

      // 已关联客户的产品或者无编辑权限的产品，不做额外判断
      if (this.product.customer || editAuth === 0) return false
      let extraAuth = this.initData?.productAuthority || 0

      switch (extraAuth) {
      case 3:
        return true
      case 2:
      case 1:
        return editAuth === extraAuth || editAuth === 3
      case 0:
        return false
      default:
        break;
      }
      return false
    },

    changeList(){
      this.$refs.changeDialog.openDialog();
    },

    // 获取归档工单数量
    async getCount(){
      const params = {
        productId: this.product.id
      }
      const {code, message, result} = await getCount(params);
      if(code === 0){
        this.archiveCount = result.archiveCount;
        this.isArchiveView = result.isArchiveView;
      }else{
        this.$notify({
          title: this.$t('common.base.fail'),
          message,
          type: 'error'
        });
      }
    },
    unRelationSuc(){
      window.location.reload();
    },
    dialogBind(e) {

      if (this.dialogType == 'linkQrcode') {
        bindQrcode({
          productId: this.productId,
          qrocdeId: e.qrcodeId,
        })
          .then((res) => {
            if (res.status)
              return this.$platform.notification({
                title: this.$t('common.base.fail'),
                message: res.message || this.$t('product.tips.unknownError'),
                type: 'error',
              });

            this.$refs.publicDialog.close();

            this.dataInfo['qrcodeId'] = e.qrcodeId;
            this.$nextTick(() => {
              this.createCode();
              this.queryAppletQrCode(this.dataInfo.qrcodeId)
            });

            this.$refs.producInfoRecord?.searchRecord();
            this.fetchStatisticalData()
            return this.$platform.notification({
              title: this.$t('product.tips.bindQrcodeSuccess'),
              type: 'success',
            });
          })
          .catch((e) => console.error('e', e))
          .finally(() => {
            this.$refs.publicDialog.changeLoading(false);
          });
      } else {
        setPageRelationProduct({
          catalogId: e.catalogId,
          productIds: [this.productId],
        })
          .then((res) => {
            if(res.code == 0){

              (this.dataInfo['catalogId'] = e.catalogId),
              this.$nextTick(()=>{
                this.$refs.catalogView.resetPage(e.catalogId);
                this.$refs.publicDialog.close();

                this.$refs.producInfoRecord?.searchRecord();
                this.fetchStatisticalData()
              })

            }

          })
          .finally(() => {
            this.$refs.publicDialog.changeLoading(false);
          });
      }
    },
    getAddress(field) {
      if (!field) return '';
      return formatAddress(field);
    },
    openPublicDialog(e) {
      this.dialogType = e;
      this.$refs.publicDialog.open();
    },
    // 关联客户
    openBindDialog(){
      this.$refs.customerBind.open();
    },
    openDownloadCodeDialog(type) {
      this.codeType = type
      this.$refs.downloadCodeDialog.open();
    },
    async unbindQrcodeFromProduct() {
      if (
        !(await this.$platform.confirm(
          this.$t('product.detail.tips.tip3')
        ))
      )
        return;

      unbindQrcode({
        productId: this.product.id,
      })
        .then((res) => {
          if (res.status)
            return this.$platform.notification({
              title: this.$t('common.base.fail'),
              message: ((h) => <div> {res.message || this.$t('product.tips.unknownError')} </div>)(
                this.$createElement
              ),
              type: 'error',
            });

          this.dataInfo.qrcodeId = null;
          this.$refs.producInfoRecord?.searchRecord();
          this.fetchStatisticalData();

          this.$platform.notification({
            title: this.$t('common.base.deleteSuccess'),
            type: 'success',
          });
        })
        .catch((e) => {
          console.error('e', e);
        });
    },
    createCode() {
      if (this.dataInfo && !this.dataInfo.qrcodeId) return;
      if (!this.$refs.qrcode) return;

      let url = `${window.location.origin}/qrcode/${
        this.initData.domain
      }?qrcodeId=${this.dataInfo.qrcodeId}`;

      this.$refs.qrcode.innerHTML = '';
      this.$nextTick(() => {
        let qrcode = new QRCode(this.$refs.qrcode, {
          text: url,
          width: 220,
          height: 220,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H,
        });
      });
    },

    // 更新客户名称的样式
    updateProductNameStyle() {
      let cnEl = this.$refs.customerName;
      let width = cnEl.offsetWidth;
      let maxWidth = cnEl.closest('h3').offsetWidth;

      this.showWholeName = maxWidth - 20 < width ? 0 : -1;
    },
    refreshProduct() {
      getProductDetail({
        id: this.productId,
      })
        .then((res) => {
          if (!res) return;
          this.newestProduct = res;


          this.dataInfo = res;

          if (this.newestProduct.qrcodeId) {
            this.createCode();
          }
        })
        .catch((e) => console.error('e', e));
    },
    editProduct(id) {
      let currTabId = window.frameElement.dataset.id;
      openAccurateTab({
        type:PageRoutesTypeEnum.PageProductEdit,
        key:this.product.id,
        closeNowPage:true,
        fromId:currTabId
      })
    },
    addProduct(id) {
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateProduct,
        reload: true,
      })
    },
    openRemindDialog(remind) {
      this.$refs.addRemindDialog.openDialog(remind);
    },
    async deleteProduct() {
      try {
        if (!(await this.$platform.confirm(this.$t('product.detail.tips.tip4')))) return;

        const result = await deleteProductByIds(this.productId);
        if (!result.status) {
          const id = window.frameElement.dataset.id;
          const fromId = window.frameElement.getAttribute('fromid');
          this.$platform.closeTab(id);
          this.$platform.refreshTab(fromId);
        }
      } catch (e) {
        console.error('product-view delete product error', e);
      }
    },
    goBack() {
      parent.frameHistoryBack(window);
    },
    /** 从客户创建工单 */
    createTask(typeId) {
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: 'createTask',
      //   title: '新建工单',
      //   close: true,
      //   url: `/task/createFromProduct/${
      //     this.productId
      //   }?defaultTypeId=${typeId}`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateTaskFromProduct,
        key: this.productId,
        params: `defaultTypeId=${typeId}`,
        fromId
      })
    },
    /** 从客户创建事件 */
    createEvent(typeId) {
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: 'createEvent',
      //   title: '新建事件',
      //   close: true,
      //   url: `/event/createFromProduct/${
      //     this.productId
      //   }?defaultTypeId=${typeId}`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateEventFromProduct,
        key: this.productId,
        params: `defaultTypeId=${typeId}`,
        fromId
      })
    },
    /** 从客户创建计划工单 */
    createPlanTask(typeId) {
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: 'createPlan',
      //   title: '新建计划任务',
      //   close: true,
      //   url: `/task/planTask/create?defaultTypeId=${typeId}&productId=${
      //     this.productId
      //   }`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PagePlanTaskCreate,
        params: `defaultTypeId=${typeId}&productId=${this.productId}`,
        fromId
      })
    },
    // 打开客户新tab
    openCustomer() {
      if (this.product.customer && !this.product.customer.id) return;

      const customerId = this.product.customer.id;

      // this.$platform.openTab({
      //   id: `customer_view_${customerId}`,
      //   title: '客户详情',
      //   close: true,
      //   url: `/customer/view/${customerId}?noHistory=1`,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        params: 'noHistory=1',
      })
    },
    // 获取统计数量
    async fetchStatisticalData() {
      try {
        let params = {
          productId: this.product.id,
        };
         await productStatisticsInit(params)
          .then((result) => {
            if (!result) return;
            this.statisticalData = result;
            this.tabs = this.buildTabs();
            this.upDataRightTabBarList();
          })
          .catch((err) => console.error(err));
      }catch(err){
        console.log(err)
      }

    },
    // 构建tab
    buildTabs() {
      const {
        taskQuantity,
        eventQuantity,
        unfinishedTaskQuantity,
        unfinishedEventQuantity,
        recordQuantity,
        plantaskQuantity,
        remindQuantity,
        qualityQuantity,
        contractQuantity
      } = this.statisticalData;

      return [
        {
          displayName: `${this.tabsName['infoRecord']}(${recordQuantity || 0})`,
          component: InfoRecord.name,
          slotName: 'record-tab',
          show: true,
        },
        {
          displayName: taskQuantity
            ? `${this.tabsName['task']}(${unfinishedTaskQuantity || 0}/${
              taskQuantity >= 1000 ? '999+' : taskQuantity
            })`
            : `${this.tabsName['task']}(0)`,
          component: TaskTable.name,
          show: true,
        },
        {
          displayName: eventQuantity
            ? `${this.tabsName['event']}(${unfinishedEventQuantity || 0}/${
              eventQuantity >= 1000 ? '999+' : eventQuantity
            })`
            : `${this.tabsName['event']}(0)`,
          component: EventTable.name,
          show: true,
        },
        {
          displayName: `${this.tabsName['contract']}(${contractQuantity || 0})`,
          component: CustomerContractTable.name,
          show: this.contractBtnCray
        },
        {
          displayName: `${this.tabsName['plan']}(${plantaskQuantity || 0})`,
          component: PlanTable.name,
          show: this.allowCreatePlanTask && this.isShowPlanTask,
        },
        {
          displayName: `${this.tabsName['remind']}(${remindQuantity || 0})`,
          component: RemindTable.name,
          show: this.isShowCustomerRemind,
        },
        {
          displayName: `${this.tabsName['qualityInfo']}(${remindQuantity || 0})`,
          component: ComponentNameEnum.QualityInfoRecord,
          show: this.isOpenQuality,
        },
      ].filter((tab) => tab.show);
    },

    selectTab(tab) {
      this.currTab = tab;
    },

    openDialog(action) {
      if (action === 'address') {
        this.$refs.EditAddressDialog.openDialog();
      } else if (action === 'contact') {
        this.$refs.EditContactDialog.openDialog();
      } else if (action === 'remark') {
        this.$refs.addRemarkDialog.openDialog();
      } else if (action === 'remind') {
        this.$refs.addRemindDialog.openDialog();
      }
    },
    alterData() {
      // this.$platform.openTab({
      //   id: 'productV2_catalog_edit',
      //   title: '产品类型编辑',
      //   close: true,
      //   url: `/productV2/catalog/edit?id=${this.dataInfo.id}`,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductCatalogCreate,
        params: `id=${this.dataInfo.id}`,
      })
    },
    creatData() {
      // this.$platform.openTab({
      //   id: 'productV2_catalog_edit',
      //   title: '产品类型编辑',
      //   close: true,
      //   url: '/productV2/catalog/edit',
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductCatalogEdit
      })
    },
    openProductMenuTab(id) {
      let fromId;
      try {
        fromId = window.frameElement.getAttribute('id');
      } catch (error) {

      }
      // this.$platform.openTab({
      //   id: `productV2_catalog_view_${id}`,
      //   title: '产品类型详情',
      //   close: true,
      //   url: `/productV2/catalog/view?id=${id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductV2CatalogView,
        key: id,
        params: `id=${id}`,
        fromId
      })
    },
    changeDataInfo(e, key = 'pathName'){
      let obj = {...this.dataInfo, ...e}
      // 如果开启了产品目录分列展示
      if (obj[key] && this.productMenuSplit) {
        const pathName = obj[key].split('/')
        // 如果只有一级产品类型，产品目录显示空
        if (pathName.length > 1) {
          obj.catalogPathName = pathName[pathName.length - 1]
          const productMenu = pathName.slice(0, pathName.length - 1)
          obj.productMenu = productMenu.join(' / ')
        } else {
          obj.productMenu = ''
        }
      }
      this.$set(this, 'dataInfo', obj)
    },
    async setQualityTabStorage() {
      const productQualityTab = await StorageUtil.storageGet(StorageKeyEnum.ProductQualityTab, null, StorageModuleEnum.Task)
      if (productQualityTab === null) {
        this.isOpenQualityChanged = true
        if (this.isGetCardCached) {
          this.changeQualityTab()
        }
      }
    },
    // 查询小程序二维码
    async queryAppletQrCode(qrcodeId){
      const params = {
        qrcodeId
      }
      const {result} = await queryAppletQrCode(params)
      if(result){
        this.miniProgramCodeImg = result.ossUrl
        this.appletCodeId = result.id
      }
    },
    /**
     * @des 初始化tabBar
     */
     async initRightTabBar(){
      try {
        const count = await getSystemViewLayout()
        this.taskLayout = count?.baseLayout || 2
        this.formCellCount = count?.formCellCount || 1
      } catch (error) {
        console.warn(error, 'error try catch initBanner');
      }
      let { TabBarListItemKey:tabName, TabBarListItemLabel:tabLabel, TabBarListItemShow:tabShow, TabBarCardInfoType:tabIsCardType, TabCardInfoSingle:tabIsCardSingle, TabBarListItemType:tabType } = BaseTabBarUsualEnum;
      let cardInfoList = [];
      this.rightTabBarLoading = true;
      // 通栏模式tabPosition默认left
      if (this.taskLayout === 1) {
        this.tabPosition = 'left'
      }
      try {
        // 获取附加组件列表
        let { result, code, message } = await getEnabledCardInfo({cardType:this.propsForSubComponents.cardType});
        if(code !== 0){
          throw message
        }
        cardInfoList = result.map(item=>{
          const { id, name, fields} = item;
          return {
            ...item,
            fields: migration(fields || []),
            [tabName]: `${tabIsCardSingle}${id}`,
            [tabLabel]: name,
            [tabShow]:true,
            [tabType]:tabIsCardType
          }
        })
      } catch (error) {
        console.warn(error, 'error try catch getEnabledCardInfo');
      }
      let barArr = [
        {[tabName]:"info-record", disabled:true, [tabLabel]:`${this.tabsName['infoRecord']}(${this.statisticalData.recordQuantity || 0})`, [tabShow]:true},
        ...(this._isShowTaskModule ? [{[tabName]:"task-table", [tabLabel]: (this.statisticalData.taskQuantity + this.archiveCount) ? `${this.tabsName['task']}(${this.statisticalData.unfinishedTaskQuantity || 0}/${this.statisticalData.taskQuantity +this.archiveCount >= 1000? '999+': this.statisticalData.taskQuantity + this.archiveCount})`: `${this.tabsName['task']}(0)`, [tabShow]:true }] : []),
        ...(this._isShowEventModule ? [{[tabName]:"event-table", [tabLabel]: this.statisticalData.eventQuantity ? `${this.tabsName['event']}(${this.statisticalData.unfinishedEventQuantity || 0}/${ this.statisticalData.eventQuantity >= 1000? '999+' : this.statisticalData.eventQuantity})`: `${this.tabsName['event']}(0)`, [tabShow]:true }] : []),
        ...(this.contractBtnCray && this._isShowCustomerContract ? [{[tabName]:"product-contract", [tabLabel]:`${this.tabsName['contract']}(${this.statisticalData.contractQuantity || 0})`, [tabShow]:true }] : []),
        ...(this.smartPlanGray ? [{[tabName]: 'smart-plan-table', [tabLabel]: this.tabsName['smartPlan'], [tabShow]:true }] : []),
        ...(this.allowCreatePlanTask && this.isShowPlanTask ? [{[tabName]:"plan-table", [tabLabel]: `${this.tabsName['plan']}(${this.statisticalData.plantaskQuantity || 0})`, [tabShow]:true }] : []),
        ...(this.isShowCustomerRemind ? [{[tabName]:"remind-table", [tabLabel]:`${this.tabsName['remind']}(${this.statisticalData.remindQuantity || 0})`, [tabShow]:true }] : []),
        ...(this.isOpenQuality && this._isShowProductQuality ? [{[tabName]:"product-quality-info", [tabLabel]:this.tabsName['productQualityInfo'], [tabShow]:true }] : []),
        ...(this.isShowFaultLibrary ? [{[tabName]:"fault-library-table", [tabLabel]:this.tabsName['faultLibrary'], [tabShow]:true }] : []),
        ...cardInfoList,
      ]
      barArr.forEach(tab => {
        tab.needTrack = true
        tab.position = 'right'
      })
      let parasm_ = {
        equipment:StorageHttpParamsForTerminalType.PC,
        bizType:StorageHttpParamsForModuleType.Product,
        bizTypeId:'0'
      }
      try {
        // 获取tabbar用户行为缓存/*  */
        let storageList = await getStorageForDetailTabbar(parasm_);
        if(storageList.status !== 0) {
          throw storageList.message
        }
        let storageList_ = storageList.data.map(item=>{
          const { cardId, checked} = item;
          return {
            [tabName]:cardId,
            [tabShow]:checked
          }
        })
        barArr = computedTabList(barArr, storageList_)
      } catch (error) {
        console.warn(error, 'error try catch getStorageForDetailTabbar');
      }
      this.tabBarList = barArr;
      this.$nextTick(()=>{
        this.rightTabBarLoading = false;
        let firstItem = barArr && barArr.find(item=>item[tabShow])
        this.currTabRight = firstItem?.[tabName];
      })
      this.rightTabBarList = this.tabBarList;

      this.leftActiveTab = this.leftTabBarList[0].tabName;
      this.leftActiveTabItem = this.leftTabBarList[0];
      this.rightActiveTab = this.rightTabBarList[0].tabName;
      this.rightActiveTabItem = this.rightTabBarList[0];

      this.taskLayoutTabBarList = cloneDeep([...this.leftTabBarList,...this.rightTabBarList].filter(item => item.tabShow));

    },
    tabBarChangeItem(item){
      let { TabBarListItemKey:tabName,  TabBarListItemType:tabType, TabBarCardInfoType } = BaseTabBarUsualEnum;
      let { position } = item
      // this.$refs.rightContent?.scrollTo(0, 0)
      this.tabPosition = position;
      if(this.taskLayout === 1 || position == 'left') {
        this.leftActiveTab = item[tabName];
        this.leftActiveTabItem = item
      }

      // 右侧导航
      if (position == 'right') {
        this.rightActiveTab = item[tabName];
        this.rightActiveTabItem = item;
      }

      if (item[tabType] == TabBarCardInfoType) {
        this.$nextTick(() => {
          let taskDetailCard = this.$refs.taskDetailCard;
          taskDetailCard && (taskDetailCard.activeTab = item.id)
        })
      }
    },
    /**
     * @des tabbar数据发生变更钩子函数
     */
    tabBarUpdateList(list){
      const { TabBarCardInfoType, TabBarListItemKey:tabName, TabBarListItemShow:tabShow } = BaseTabBarUsualEnum;
      let list_ = list.map(item=>{
        return {
          cardId: item.type == TabBarCardInfoType ? item.id : item[tabName],
          checked: item[tabShow]
        }
      })
      let parasm_ = {
        equipment:StorageHttpParamsForTerminalType.PC,
        bizType:StorageHttpParamsForModuleType.Product,
        bizTypeId:'0',
        cardList:list_
      }
      setStorageForDetailTabbar(parasm_)
    },
    /** 更新右侧tab 数据 */
    upDataRightTabBarList() {
      console.log(this.tabs)
      this.rightTabBarList.forEach(item => {
        const tab = this.tabs.find(ele => ele.component === item.tabName);
        if (tab) {
          item.tabLabel = tab.displayName;
        }
      });
    },
    // 是否是附加组件
    isAddOn (key) {
      let str = BaseTabBarUsualEnum.TabCardInfoSingle;
      return key.startsWith(str)
    },
    getBtnsTrackData(id, data) {
      return this.$track.formatParams(id, data, 'DETAIL_BTNS_GROUP')
    },
    handleMoreOperationCommand(command) {
      if (command == 'smartPlan') {
        this.$refs.createSmartPlanDialog.open()
      } else if (command?.type == 'trigger') {
        this.handleManualTrigger(command.id, [this.product.id])
      }
    }
  },
  components: {
    [EventTable.name]: EventTable,
    [TaskTable.name]: TaskTable,
    [PlanTable.name]: PlanTable,
    [RemindTable.name]: RemindTable,
    [InfoRecord.name]: InfoRecord,
    [RemindDialog.name]: RemindDialog,
    [PublicDialog.name]: PublicDialog,
    [DownloadCodeDialog.name]: DownloadCodeDialog,
    [EditContactDialog.name]: EditContactDialog,
    [ProductContactTable.name]: ProductContactTable,
    MiniTable,
    [CatalogView.name]: CatalogView,
    [TaskCard.name]: TaskCard,
    [QualityInfoRecord.name]: QualityInfoRecord,
    [CustomerBind.name]:CustomerBind,
    [SmartPlanTable.name]: SmartPlanTable,
    [noAuth.name]:noAuth,
    [CustomerContractTable.name]: CustomerContractTable,
    BaseBarV3,
    ProductQualityInfo,
    ProductFaultLibraryTable,
    FormCellChange,
    BaseTileLayoutTabBar,
    BaseEventTable,
  },
};
